from app.db.models.users import User
from app.db.models.balances import Balances
from app.errors import BalanceLimit
from app.libs.enums import AVAILABLE_TASK_GROUP_TUPLE


class BalancesOne(object):
    def __init__(self, username=None, uid=None, obj_balances=None):
        self.obj_balance = None

        if username:
            obj_user = User.objects.filter(username=username).first()
            self.obj_balance = Balances.objects.filter(uid=obj_user.pk).first()
        elif uid:
            self.obj_balance = Balances.objects.filter(uid=uid).first()
        elif obj_balances:
            self.obj_balance = obj_balances

    def inc_manual_task_used(self, task_type, numbers, only_check=False):
        if task_type not in AVAILABLE_TASK_GROUP_TUPLE:
            bkey = fkey = f"{task_type}ManualTask"
        else:
            fkey = f"{task_type}Task"
            bkey = f"{task_type}MaxTask"
        if not getattr(self.obj_balance.feature, fkey):
            raise BalanceLimit(msg="请先升级套餐服务")

        if numbers > 0:
            manual_task_number = getattr(self.obj_balance.balance, bkey)
            if manual_task_number.used + numbers > manual_task_number.total:
                raise BalanceLimit(msg="剩余可使用监测次数不足")

        if not only_check:
            update_dict = {
                f"inc__balance__{bkey}__used": numbers
            }
            self.obj_balance.update(**update_dict)
            self.obj_balance.reload()
